/*
 * @Author: MB's X13 374870361@qq.com
 * @Date: 2024-05-21 18:54:15
 * @LastEditors: MB's X13 374870361@qq.com
 * @LastEditTime: 2024-05-21 20:09:16
 * @Description:
 */
package main

import "fmt"

// 返回 a、b 中最大值.
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func testMax() {
	x := 3
	y := 4
	z := 5

	max_xy := max(x, y) // 调用函数max(x, y)
	max_xz := max(x, z) // 调用函数max(x, z)

	fmt.Printf("max(%d, %d) = %d\n", x, y, max_xy)
	fmt.Printf("max(%d, %d) = %d\n", x, z, max_xz)
	fmt.Printf("max(%d, %d) = %d\n", y, z, max(y, z)) // 也可在这直接调用它
}

// 多个返回值
// 返回 A+B 和 A*B
func SumAndProduct(A, B int) (int, int) {
	return A + B, A * B
}

func SumAndProduct_02(A, B int) (add int, Multiplied int) {
	add = A + B
	Multiplied = A * B
	return
}

func testSumAndProduc() {
	x := 3
	y := 4

	xPLUSy, xTIMESy := SumAndProduct(x, y)

	fmt.Printf("%d + %d = %d\n", x, y, xPLUSy)
	fmt.Printf("%d * %d = %d\n", x, y, xTIMESy)

	x, y = 2, 5
	xPLUSy, xTIMESy = SumAndProduct_02(x, y)

	fmt.Printf("%d + %d = %d\n", x, y, xPLUSy)
	fmt.Printf("%d * %d = %d\n", x, y, xTIMESy)
}

// 可变参数
func printMultiInt(arg ...int) {
	for _, n := range arg {
		fmt.Printf("And the number is: %d\n", n)
	}
}

func testPrintMultiInt() {

	printMultiInt(1, 2, 3)
}

func add1(a int) int {
	a = a + 1
	return a
}

func add2(a *int) int {
	*a = *a + 1
	return *a
}

func testAdd() {
	x := 3

	fmt.Println("x = ", x) // 应该输出 "x = 3"

	add1(x)
	fmt.Println("x = ", x) // 应该输出 "x = 3"

	add2(&x)
	fmt.Println("x = ", x) // 应该输出 "x = 4"
}

type testInt func(int) bool // 声明了一个函数类型

func isOdd(integer int) bool {
	if integer%2 == 0 {
		return false
	}
	return true
}

func isEven(integer int) bool {
	if integer%2 == 0 {
		return true
	}
	return false
}

// 声明的函数类型在这个地方当做了一个参数

func filter(slice []int, f testInt) []int {
	var result []int
	for _, value := range slice {
		if f(value) {
			result = append(result, value)
		}
	}
	return result
}

func testFuncAsType() {
	slice := []int{1, 2, 3, 4, 5, 7}
	fmt.Println("slice = ", slice)
	odd := filter(slice, isOdd) // 函数当做值来传递了
	fmt.Println("Odd elements of slice are: ", odd)
	even := filter(slice, isEven) // 函数当做值来传递了
	fmt.Println("Even elements of slice are: ", even)
}

func main() {
	testMax()

	testSumAndProduc()

	testPrintMultiInt()

	testAdd()

	testFuncAsType()
}
